using UnityEngine;

namespace MyTools{

//抛物线轨迹
public class ParabolicMotion2D
{
    private float g = 9.81f; // 重力加速度
    private Vector3 startPoint;
    private Vector3 endPoint;
    private float totalTravelTime;
    private float horizontalVelocity; // 水平速度

    // 构造函数，初始化抛物线参数
    public ParabolicMotion2D(Vector3 start, Vector3 end, float totalTime)
    {
        startPoint = start;
        endPoint = end;
        totalTravelTime = totalTime;
        CalculateHorizontalVelocity();
    }

    // 计算水平速度
    private void CalculateHorizontalVelocity()
    {
        float horizontalDistance = endPoint.x - startPoint.x;
        horizontalVelocity = horizontalDistance / totalTravelTime;
    }

    // 基于目前的时间，返回在轨迹上的位置和切线方向
    public (Vector2 position, Vector2 tangent) GetPositionAndTangentAtTime(float currentTime)
    {
        if (currentTime > totalTravelTime)
            currentTime = totalTravelTime; // 防止超出时间范围

        // 水平位置是线性插值
        float x = startPoint.x + horizontalVelocity * currentTime;

        // 垂直位置考虑重力加速度
        float y = startPoint.y - (0.5f * g * currentTime * currentTime);

        Vector2 position = new Vector2(x, y);

        // 计算切线斜率
        float dy = -g * currentTime;
        Vector2 tangent = new Vector2(1, dy).normalized; // 切线向量

        return (position, tangent);
    }
}
}